//
//  WBNewFeatureView.swift
//  个人微博
//
//  Created by 任聪聪 on 2018/1/23.
//  Copyright © 2018年 任孜聪. All rights reserved.
//

import UIKit

class WBNewFeatureView: UIView {

    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var pageControl: UIPageControl!
    @IBOutlet weak var enterButton: UIButton!
    @IBAction func clickEnter() {
    }
    class func newFeatureView()->WBNewFeatureView{
        let nib = UINib(nibName: "WBNewFeatureView", bundle: nil)
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! WBNewFeatureView
        //使用XIB的加载的视图默认是600X600的
        v.frame = UIScreen.main.bounds
        return v
    }
    override func awakeFromNib() {
        let count = 4
        let rect = UIScreen.main.bounds
        for i in 0..<count {
            let imageName = "new_feature_\(i+1)"
            let imageView = UIImageView(image: UIImage(named: imageName))
            //设置大小都想x轴正方向移动i个图片宽度
            imageView.frame = rect.offsetBy(dx: CGFloat(i)*rect.width, dy: 0)
            scrollView.addSubview(imageView)
        }
        //指定scrollView的属性
        scrollView.contentSize = CGSize(width: CGFloat(count + 1)*rect.width, height: rect.height)
        scrollView.bounces = false
        //设置垂直滑轮
        scrollView.showsVerticalScrollIndicator = false
        //设置水平滑轮
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.isPagingEnabled = true
        //隐藏进入按钮
        enterButton.isHidden = true
        //设置scrollView的代理
        scrollView.delegate = self
    }
}
extension WBNewFeatureView:UIScrollViewDelegate{
    //结束拖拽，手指刚离开视图的那一刻
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        //1.计算页数
        var page = (scrollView.contentOffset.x/scrollView.bounds.width)
        //2.计算是否到达最后一页,如果是就删除当前视图
        if page == (CGFloat)(scrollView.subviews.count) {
            removeFromSuperview()
        }
        //3.判断进入微博按钮是否显示如果是最后一页则显示
        enterButton.isHidden = page != (CGFloat)(scrollView.subviews.count-1)
    }
    //已经开始滚动调用此方法
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        //计算当前偏移量
        var page = (Int)((scrollView.contentOffset.x/scrollView.bounds.width) + 0.5)
        //计算当前页面
        pageControl.currentPage = Int(page)
        //设置隐藏分页控件
        pageControl.isHidden = page == scrollView.subviews.count
    }
}
